package com.yuji.aacar.core.cores.utils;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;

/**
 * <li>Package:com.ttp.core.cores.utils
 * <li>Author: lining
 * <li>Date: 2017/5/10
 * <li>Description: 崩溃日志
 */

public class CoreCrashManager implements UncaughtExceptionHandler {

    // CrashHandler实例
    private static CoreCrashManager instance;
    private static final String TAG = "<<CrashCatch>>";

    public static final int MEMORY_LOG_FILE_MAX_SIZE = 400 * 1024; // 内存中日志文件最大值，1K

    private static Context context;
    private SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private OutputStreamWriter writer;
    private File file;
    private File crashLogFile;

    private UncaughtExceptionHandler mDefaultHandler;

    /**
     * 初始化崩溃日志和本地文件夹
     * @param context
     * @param appName   应用名称
     * @param LogFileName 日志文件名称
     * @return
     */
    public static CoreCrashManager getInstance(Context context,String appName, String LogFileName) {
        CoreCrashManager inst = instance;
        if (inst == null) {
            synchronized (CoreCrashManager.class) {
                inst = instance;
                if (inst == null) {
                    inst = new CoreCrashManager(context.getApplicationContext(), appName, LogFileName);
                    instance = inst;
                }
            }
        }
        return inst;
    }

    private CoreCrashManager(Context aContext, String appName, String LogFileName) {
        context = aContext;
        init(aContext, appName, LogFileName);
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 记录日志服务的基本信息 防止日志服务有错，在LogCat日志中无法查找 此日志名称为ttpai.log
     *
     * @param ex
     */
    private void recordLogServiceLog(Throwable ex) {

        // 1.获取当前程序的版本号. 版本的id
        String versioninfo = CoreDeviceUtil.getVersionInfo(context);

        // 2.获取手机的硬件信息.
        String mobileInfo = CoreDeviceUtil.getMobileInfo();

        // 3.把错误的堆栈信息 获取出来
        String errorinfo = getErrorInfo(ex);

        // 4.用户信息
        Object userId = CorePersistenceUtil.getObject(CorePersistenceUtil.USERID);
        Object phoneNumber = CorePersistenceUtil.getObject(CorePersistenceUtil.PHONENUMBER);

        String msg =  "userInfo: "+userId +" phone: "+ phoneNumber +  "\r\n"+" phoneInfo: "+versioninfo + mobileInfo + "errorInfo: " + errorinfo;
        Log.e(TAG, " exception catch :" + msg);
        CoreFileUtil.writeFileToPath(crashLogFile, msg);
    }



    private void init(Context aContext, String appName, String logFileName) {
        crashLogFile = CoreFileUtil.createAllLogDirAccordingAppName(aContext, appName,logFileName);
    }



    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // TODO Auto-generated method stub
        recordLogServiceLog(ex);
        mDefaultHandler.uncaughtException(thread, ex);
    }

    /**
     * 获取错误的信息
     *
     * @param arg1
     * @return
     */
    public static String getErrorInfo(Throwable arg1) {
        Writer writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        arg1.printStackTrace(pw);
        pw.close();
        String error = writer.toString();
        return error;
    }


}
